package com.daxia.ogmall.web.controller.m;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daxia.ogmall.common.DesignType;
import com.daxia.ogmall.common.MyJSONObject;
import com.daxia.ogmall.common.NeedLogin;
import com.daxia.ogmall.common.Sex;
import com.daxia.ogmall.dto.DesignCollectionDTO;
import com.daxia.ogmall.dto.DesignDTO;
import com.daxia.ogmall.dto.DesignerDTO;
import com.daxia.ogmall.dto.HouseStyleDTO;
import com.daxia.ogmall.dto.HouseTypeDTO;
import com.daxia.ogmall.exception.BizException;
import com.daxia.ogmall.model.Design;
import com.daxia.ogmall.model.Designer;
import com.daxia.ogmall.model.HouseStyle;
import com.daxia.ogmall.model.HouseType;
import com.daxia.ogmall.model.User;
import com.daxia.ogmall.support.MPage;
import com.daxia.ogmall.support.Page;
import com.daxia.ogmall.util.BeanMapper;
import com.daxia.ogmall.util.JsoupUtil;

@Controller
@RequestMapping(value = "/m/design", produces = "application/json;charset=UTF-8")
public class MDesignController extends MBaseController {
    
	private static final Logger logger = Logger.getLogger(MDesignController.class);

	@ResponseBody
    @RequestMapping("getDesignByDesignerId")
    public String getDesignByDesignerId(String designerId, DesignDTO dto, MPage page) throws Exception {
    	super.assertNotBlank(designerId, "设计师ID不能为空.");
    	
    	DesignerDTO designerDTO = designerService.load(Long.parseLong(designerId));
    	Designer designerQuery = new Designer();
    	designerQuery.setId(designerDTO.getId());
    	
    	MyJSONObject data = new MyJSONObject();
    	JSONArray array = new JSONArray();
    	
    
    	dto.setDesigner(designerQuery);
    	List<DesignDTO> designDTOList = designService.find(dto, page);
    	for (DesignDTO designDTO : designDTOList) {
    		JSONObject obj = new JSONObject();
    		String headImage = designDTO.getHeadImage();
    		if (StringUtils.isBlank(headImage)) {
    			List<String> imageList = designDTO.getImageList();
    			if (CollectionUtils.isNotEmpty(imageList)) {
    				headImage = imageList.get(0);
    			}
    		}
    		obj.put("designImage", headImage);
        	obj.put("designerHeadImage", designerDTO.getUser().getHeadImage());
        	obj.put("title", designDTO.getTitle());
        	obj.put("images", designDTO.getImageList());
        	String keywords = "";
        	if (designDTO.getHouseStyle() != null) {
        		keywords +=  designDTO.getHouseStyle().getName();
        	}
        	if (designDTO.getHouseType() != null) {
        		keywords += "/" + designDTO.getHouseType().getName();
        	}
        	if (StringUtils.isNotBlank(designDTO.getArea())) {
        		keywords += "/" + designDTO.getArea();
        	}
        	obj.put("keywords", keywords);
        	
        	obj.put("price", "￥" + designDTO.getPrice());
        	obj.put("id", designDTO.getId());
        	obj.put("content", JsoupUtil.parseDocument(designDTO.getContent()));
        	obj.put("details", designDTO.getDetails());
        	obj.put("type", designDTO.getType());
    		obj.put("typeRemark", DesignType.getByValue(designDTO.getType()).getRemark());
        	array.add(obj);
    	}
   
    	data.put("myCollections", array);
    	data.put("fanCount", designerDTO.getFanCount());
    	setPageInfo(data, page);
   		return toJson(data);
    }
    
	/**
	 * find designCollections by paging.
	 * @param dto
	 * @param page
	 * @return
	 * @throws Exception
	 */
    @ResponseBody
    @RequestMapping("list")
    public String list(DesignDTO dto, Long cityID, Long homeID, Long areaID, Long styleID, MPage page) throws Exception {
    	if (dto.getType() == null) {
    		dto.setType(DesignType.Images.getValue());
    	}
    	if (homeID != null) {
    		dto.setHouseType(new HouseType());
    		dto.getHouseType().setId(homeID);
    	}
    	if (areaID != null) {
    		dto.setHouseAreaTag(areaID.intValue());
    	}
    	if (styleID != null) {
    		dto.setHouseStyle(new HouseStyle());
    		dto.getHouseStyle().setId(styleID);;
    	}
    	if (cityID != null) {
    		Designer designerQuery = new Designer();
			dto.setDesigner(designerQuery);
    	}
        List<DesignDTO> designDTOs = designService.find(dto, page);
        JSONArray designArray = new JSONArray();
        
        for (DesignDTO designDTO : designDTOs) {
        	designArray.add(buildDesignJson(designDTO));
        }
        
        MyJSONObject json = new MyJSONObject();
        super.setPageInfo(json, page);
        json.put("designInfos", designArray);

        return toJson(json);
    }

	private JSONObject buildDesignJson(Design model) {
		DesignDTO designDTO = null;
		if (model instanceof DesignDTO) {
			designDTO = (DesignDTO) model;
		} else {
			designDTO = BeanMapper.map(model, DesignDTO.class);
		}
		MyJSONObject obj = new MyJSONObject();
		obj.put("userId", designDTO.getUser() == null ? null : designDTO.getUser().getId());
		obj.put("designId", designDTO.getId());
		obj.put("headImage", designDTO.getHeadImage());
		obj.put("images", designDTO.getImageList());
		obj.put("content", JsoupUtil.parseDocument(designDTO.getContent()));
		obj.put("title", designDTO.getTitle());
		obj.put("theme", designDTO.getTheme());
		obj.put("area", designDTO.getArea() + "m²");
		obj.put("type", designDTO.getType());
		obj.put("typeRemark", DesignType.getByValue(designDTO.getType()).getRemark());
		obj.put("3dUrl", designDTO.getView3dURL());
		obj.put("vrUrl", designDTO.getVRURL());
		
		DesignerDTO designerQuery = new DesignerDTO();
		User userQuery = new User();
		userQuery.setId(designDTO.getUser().getId());
		designerQuery.setUser(userQuery);
		DesignerDTO designerDTO = designerService.findOne(designerQuery);
		
		MyJSONObject designerInfo = new MyJSONObject();
		if (designerDTO != null) {
			designerInfo.put("designerId", designerDTO.getId());
			designerInfo.put("userId", designerDTO.getUser().getId());
			String username = "";
			if (StringUtils.isBlank(username) && StringUtils.isNotBlank(designerDTO.getUser().getRealName())) {
				username = designerDTO.getUser().getRealName();
			}
			if (StringUtils.isBlank(username) && StringUtils.isNotBlank(designerDTO.getUser().getNickName())) {
				username = designerDTO.getUser().getNickName();
			}
			designerInfo.put("username", username);
			designerInfo.put("nickName", designerDTO.getUser().getNickName());
			designerInfo.put("userHeadImage", designerDTO.getUser().getHeadImage());
			designerInfo.put("dealCount", designerDTO.getDealCount());
			designerInfo.put("sex", designerDTO.getUser().getSex());
			designerInfo.put("sexRemark", Sex.getByValue(designerDTO.getUser().getSex()).getRemark());
		}
		
		MyJSONObject houseTypeInfo = new MyJSONObject();
		if (designDTO.getHouseType() != null) {
			houseTypeInfo.put("houseTypeId", designDTO.getHouseType().getId());
			houseTypeInfo.put("houseTypeName", designDTO.getHouseType().getName());
		}
		
		MyJSONObject houseStyleInfo = new MyJSONObject();
		if (designDTO.getHouseStyle() != null) {
			houseStyleInfo.put("houseStyleId", designDTO.getHouseStyle().getId());
			houseStyleInfo.put("houseStyleName", designDTO.getHouseStyle().getName());
		}
		if (designDTO.getCommunity() != null) {
			MyJSONObject communityInfo = new MyJSONObject();
			communityInfo.put("communityId", designDTO.getCommunity().getId());
			communityInfo.put("communityName", designDTO.getCommunity().getName());
			communityInfo.put("communityAddress", designDTO.getCommunity().getAddress());
			communityInfo.put("communityDistrict", designDTO.getCommunity().getDistrict() == null ? "" : designDTO.getCommunity().getDistrict().getName());
			communityInfo.put("communityCity", designDTO.getCommunity().getCity() == null ? "" : designDTO.getCommunity().getCity().getName());
			communityInfo.put("communityProvince", designDTO.getCommunity().getProvince() == null ? "" : designDTO.getCommunity().getProvince().getName());
			obj.put("communityInfo", communityInfo);
		}
		if (designDTO.getCommunityHouseType() != null) {
			MyJSONObject cht = new MyJSONObject();
			cht.put("communityHouseTypeName", designDTO.getCommunityHouseType().getName());
			cht.put("communityHouseTypeArea", designDTO.getCommunityHouseType().getArea());
			cht.put("communityHouseTypeImage", designDTO.getCommunityHouseType().getImage());
			obj.put("communityHouseTypeInfo", cht);
		}
      
		obj.put("houseStyleInfo", houseStyleInfo);
		obj.put("houseTypeInfo", houseTypeInfo);
		obj.put("designerInfo", designerInfo);
		return obj;
	}

    
    
    /**
     * 收藏
     * @param designerId
     * @return
     * @throws Exception
     */
    @NeedLogin
	@ResponseBody
	@RequestMapping("collect")
	public String collect(Long designId) throws Exception {
    	assertTrue(designId != null, "方案不能为空");
    	
    	Design design = new Design();
    	design.setId(designId);
    	User user = getCurrentUser();
    	
    	DesignCollectionDTO designCollectionQuery = new DesignCollectionDTO();
    	designCollectionQuery.setDesign(design);
    	User userQuery = new User();
    	userQuery.setId(user.getId());
    	designCollectionQuery.setUser(userQuery);
		List<DesignCollectionDTO> list = designCollectionService.find(designCollectionQuery, null);
		if (CollectionUtils.isNotEmpty(list)) {
			throw new BizException("不能重复收藏!");
		}
    	
    	DesignCollectionDTO c = new DesignCollectionDTO();
    	c.setDesign(design);
    	c.setUser(user);
    	designCollectionService.create(c);
		return toJson();
	}
    
    @NeedLogin
	@ResponseBody
	@RequestMapping("cancelCollect")
	public String cancelFan(Long designId) throws Exception {
    	assertTrue(designId != null, "方案不能为空");
    	DesignCollectionDTO c = new DesignCollectionDTO();
    	c.setDesign(new Design());
    	c.getDesign().setId(designId);
    	c.setUser(getCurrentUser());
    	DesignCollectionDTO db = designCollectionService.findOne(c);
    	if (db != null) {
    		designCollectionService.deleteByIdsPhysical(db.getId());
    	}
		return toJson();
	}
    
    @NeedLogin
   	@ResponseBody
   	@RequestMapping("myCollects")
   	public String myCollects(Page page) throws Exception {
    	MyJSONObject data = new MyJSONObject();
    	
    	JSONArray array = new JSONArray();
    	
    	DesignCollectionDTO query = new DesignCollectionDTO();
    	query.setUser(getCurrentUser());
    	List<DesignCollectionDTO> collectionDTOs = designCollectionService.find(query, page);
    	for (DesignCollectionDTO c : collectionDTOs) {
    		
    		array.add(buildDesignJson(c.getDesign()));
		}
    	
    	data.put("myCollections", array);
    	setPageInfo(data, page);
   		return toJson(data);
   	}
    
    private String getKeywords(Design design) {
    	String s = "";
    	if (design.getUser().getCity() != null) {
    		s += " " + design.getUser().getCity().getName();
    	}
    	if (design.getHouseStyle() != null) {
    		s += " " + design.getHouseStyle().getName();
    	}
    	
    	if (design.getHouseType() != null) {
    		s += " " + design.getHouseType().getName();
    	} else if (design.getCommunityHouseType() != null) {
    		s += " " + design.getCommunityHouseType().getName();
    	}
    	
    	if (StringUtils.isNotBlank(design.getArea())) {
    		s += design.getArea() + "平米";
    	}
    	
		return s.trim();
	}

	@ResponseBody
    @RequestMapping("images")
    public String getImages() throws Exception {
    	MyJSONObject data = new MyJSONObject();
    	JSONArray images = new JSONArray();
		List<DesignDTO> list = designService.findAll();
		for (DesignDTO dto : list) {
			for (String url : dto.getImages().split(",")) {
				images.add(url);
			}
		}
		
		data.put("images", images);
    	return toJson(data);
    }
    
    
    
    @ResponseBody
    @RequestMapping("detail")
    public String details(Long id) throws Exception {
    	logger.info("design id is : " + id);
    	
    	MyJSONObject data = new MyJSONObject();
    	
    	DesignDTO dto = designService.load(id);
    	if (dto != null) {
    		data.put("id", dto.getId());
    		data.put("headImage", dto.getHeadImage());
    		data.put("content", JsoupUtil.parseDocument(dto.getContent()));
    		data.put("type", dto.getType());
    		data.put("typeRemark", DesignType.getByValue(dto.getType()).getRemark());
    	}
    	return toJson(data);
    }
  
    
    @NeedLogin
    @ResponseBody
    @RequestMapping("upload")
    public String upload(DesignDTO designDTO, Long houseTypeID, Long houseStyleID,  HttpServletRequest request) throws Exception {
    	notNull(houseTypeID, "户型不能为空");
    	notNull(houseStyleID, "装修风格不能为空");
    	User user = getCurrentUser();
    	DesignerDTO designQuery = new DesignerDTO();
    	User userQuery = new User();
    	userQuery.setId(user.getId());
		designQuery.setUser(userQuery);
		DesignerDTO designer = designerService.findOne(designQuery);
    	
    	HouseTypeDTO houseTypeDTO = houseTypeService.load(houseTypeID);
    	HouseStyleDTO houseStyleDTO = houseStyleService.load(houseStyleID);
    	
    	String images = super.saveFilesAndReturnFileName(request);
    	if (StringUtils.isNotBlank(images)) {
    		String content = "<p>" + designDTO.getContent() + "</p>";
    		for (String image : images.split(",")) {
    			String temp = "";
    			temp += "<p><img src=" + "\"" + image + "\" style=\"width:100%\" /><br /></p>";
    			content = StringUtils.replace(content, "[@]", temp, 1);
    		}
    		designDTO.setContent(content);
    	}
    	designDTO.setType(DesignType.Images.getValue());
    	designDTO.setUser(user);
    	designDTO.setHouseType(houseTypeDTO);
    	designDTO.setHouseStyle(houseStyleDTO);
    	designDTO.setDesigner(designer);
    	designDTO.setImages(images);
    	
    	String headImage = designDTO.getHeadImage();
		if (StringUtils.isBlank(headImage)) {
			List<String> imageList = designDTO.getImageList();
			if (CollectionUtils.isNotEmpty(imageList)) {
				headImage = imageList.get(0);
				designDTO.setHeadImage(headImage);
			}
		}
    	
    	designService.create(designDTO);
    	return toJson();
    }
    
    
    /**
     * 找灵感
     * @param designDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("inspiration")
    public String inspiration(DesignDTO designDTO, MPage page) throws Exception {
    	MyJSONObject data = new MyJSONObject();
    	JSONArray designDTOInfos = new JSONArray();
    	List<DesignDTO> designDTOs = designService.find(designDTO, page);
    	for (DesignDTO dto : designDTOs) {
			JSONObject designDTOInfo = new JSONObject();
			String headImage = dto.getHeadImage();
			if (StringUtils.isNotBlank(headImage)) {
				if (CollectionUtils.isNotEmpty(dto.getImageList())) {
					headImage = dto.getImageList().get(0);
				}
			}
			designDTOInfo.put("headImage", headImage);
			designDTOInfo.put("images", dto.getImageList());
			designDTOInfos.add(designDTOInfo);
			
		}
    	
    	data.put("designInfos", designDTOInfos);
        super.setPageInfo(data, page);
    	return toJson(data);
    }
    
    

    
}
